﻿using System;
using System.Linq;
using System.Web.Optimization;
using System.Web.UI;
using Altairis.FluffyCloud.Data;

namespace Altairis.FluffyCloud.WebCore.Pages {

    public partial class Site : System.Web.UI.MasterPage {

        public bool HasNewMessages() {
            if (!this.Request.IsAuthenticated) return false;
            using (var dc = new FluffyDbContext()) {
                return dc.Messages.Any(x => x.ToUserName.Equals(this.Page.User.Identity.Name, StringComparison.CurrentCultureIgnoreCase) && !x.DateRead.HasValue);
            }
        }

        protected void Page_Load(object sender, EventArgs e) {
            // Setup page title
            this.Page.PreRenderComplete += (s, o) => { this.Page.Title += " | FluffyCloud"; };

            // Add scripts
            this.Page.Header.Controls.Add(new LiteralControl { Text = Scripts.Render("~/bundles/modernizr").ToHtmlString() });

            // Add styles
            var user = this.Context.GetUserData();
            if (user == null || string.IsNullOrWhiteSpace(user.ThemeCssUrl)) {
                // Anonymous user or theme unspecified - use default
                this.Page.Header.Controls.Add(new LiteralControl { Text = Styles.Render("~/Content/Themes/MetroInspired/green-css").ToHtmlString() });
            }
            else if (user.ThemeCssUrl.StartsWith("~")) {
                // Using embedded theme
                this.Page.Header.Controls.Add(new LiteralControl { Text = Styles.Render(user.ThemeCssUrl).ToHtmlString() });
            }
            else {
                // Using custom theme
                var link = new System.Web.UI.HtmlControls.HtmlLink();
                link.Href = user.ThemeCssUrl;
                link.Attributes["rel"] = "stylesheet";
                link.Attributes["type"] = "text/css";
                this.Page.Header.Controls.Add(link);
            }

            // Notify user about new private messages
            if (this.HasNewMessages()) {
                this.NoMessagesPlaceHolder.Visible = false;
                this.NewMessagesPlaceHolder.Visible = true;
            }
            else {
                this.NoMessagesPlaceHolder.Visible = true;
                this.NewMessagesPlaceHolder.Visible = false;
            }
        }
    }
}